class Game{
    constructor(el){
        // 存最大盒模型
        this.el = document.querySelector(el)
        this.stratBtn = document.querySelector('.start button:nth-of-type(1)')
        this.exitBtn = document.querySelector('.start button:nth-of-type(2)')
        this.startObj = document.querySelector('.start')
        this.t = null

        // 地图
        this.map = new Map(this.el)
        this.map. mapCreate()

        // 食物
        this.food = new Food(this.el)
        this.food.foodCreate()
        this.food. foodMove()

        // 蛇出来
        this.snake = new Snake(this.el)
        this.snake.snakeCreate()
        this.snake.snakeMove()
        this.snake.snakeDirection()


        this.startGame()
        
    }

     // 添加定时器方法
     snakeStart(){
        this.t = setInterval( () =>{
            this.snake.snakeMove()
            this.snakeBorder()

            let foodl = this.food.foodX
            let foodt = this.food.foodY
            let snakel = this.snake.snakeObj[0].x * 20
            let snaket = this.snake.snakeObj[0].y *20
            console.log(foodl,foodt,snakel,snaket);
            // console.log(foodl,foodt,snakel,snaket);
            if(foodl === snakel && foodt === snaket ){
                console.log(666);
               let temp = this.snake.snakeObj[ this.snake.snakeObj.length-1]
               this.snake.snakeObj.push({
                   x:temp.x,
                   y:temp.y,
                   color:temp.color,
                   el:null
               })
               this.food.foodMove()
               this.snake.snakeCreate()  //重新绘制蛇
            }

        },200)
    }

    // 判断蛇的位置是否出边框
    snakeBorder(){
        if(this.snake.snakeObj[0].x<0 || this.snake.snakeObj[0].x> 39 || this.snake.snakeObj[0].y<0 || this.snake.snakeObj[0].y>19){
            clearInterval(this.t)
            this.startObj.style.display = 'block'

        }
    }
    //开始退出游戏按钮
    startGame(){
        this.stratBtn.onclick = () => {
            this.startObj.style.display = 'none'
            this.snakeStart()
        }
        this.exitBtn.onclick = () => {
            window.close()
        }
    }
}